package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Name     string `yaml:"name"`
}

// ConsulConfig Consul配置
type ConsulConfig struct {
	Address                 string `yaml:"address"`
	HealthCheckTimeout      string `yaml:"health_check_timeout"`
	HealthCheckInterval     string `yaml:"health_check_interval"`
	DeregisterCriticalAfter string `yaml:"deregister_critical_after"`
}

// ServicesConfig 服务端口配置
type ServicesConfig struct {
	HTTPPort         int `yaml:"http_port"`
	UserRPCPort      int `yaml:"user_rpc_port"`
	PostRPCPort      int `yaml:"post_rpc_port"`
	TitleServicePort int `yaml:"title_service_port"`
}

// ServiceAddressesConfig 服务地址配置
type ServiceAddressesConfig struct {
	UserRPC      string `yaml:"user_rpc"`
	PostRPC      string `yaml:"post_rpc"`
	TitleService string `yaml:"title_service"`
}

// AppConfig 应用配置
type AppConfig struct {
	Name         string `yaml:"name"`
	Version      string `yaml:"version"`
	Environment  string `yaml:"environment"`
	StartupDelay int    `yaml:"startup_delay"`
}

// Config 总配置结构
type Config struct {
	Database         DatabaseConfig         `yaml:"database"`
	Consul           ConsulConfig           `yaml:"consul"`
	Services         ServicesConfig         `yaml:"services"`
	ServiceAddresses ServiceAddressesConfig `yaml:"service_addresses"`
	App              AppConfig              `yaml:"app"`
}

// LoadConfig 从YAML文件加载配置
func LoadConfig(configPath string) (*Config, error) {
	// 读取配置文件
	data, err := os.ReadFile(configPath)
	if err != nil {
		return nil, fmt.Errorf("读取配置文件失败: %v", err)
	}

	// 解析YAML
	var config Config
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		return nil, fmt.Errorf("解析配置文件失败: %v", err)
	}

	return &config, nil
}

// GetDSN 获取数据库连接字符串
func (c *Config) GetDSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.Database.Username,
		c.Database.Password,
		c.Database.Host,
		c.Database.Port,
		c.Database.Name)
}

// GetHTTPAddress 获取HTTP服务地址
func (c *Config) GetHTTPAddress() string {
	return fmt.Sprintf(":%d", c.Services.HTTPPort)
}

// GetUserRPCAddress 获取用户RPC服务地址
func (c *Config) GetUserRPCAddress() string {
	return fmt.Sprintf(":%d", c.Services.UserRPCPort)
}

// GetPostRPCAddress 获取帖子RPC服务地址
func (c *Config) GetPostRPCAddress() string {
	return fmt.Sprintf(":%d", c.Services.PostRPCPort)
}
